<?php

namespace Modules\Asset\Http\Controllers\Client\V1;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

use Modules\Asset\Entities\PackageSku;
use Modules\Asset\Entities\PackageOrder as Order;
use Stbz\Api\SupplyClient;

use Validator;
use ThrowException;
use Auth;
use Setting;
use DB;

// 已开出物品
class DeliverOrderController extends Controller
{
    // 预览
    public function preview(Request $req)
    {
        $rule = [
            'ids' => ['required', 'array'],  // packageSku的id数组
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();

        $user = Auth::requireLoginUser();

        $ids = $req->input('ids');

        // 所有要返售的sku
        $packageSkus = PackageSku::belongUser($user)->status('pending')->whereIn('id', $ids)->get();

        // 收货地址
        // 准备收货地址(如果有)
        $address = $user->getAddressOrDefault($req->input('address_id'));

        $skuableMaps = [];
        foreach ($packageSkus as $sku) {
            array_push($skuableMaps, [
                'skuable' => $sku,
                'total' => $sku->total
            ]);
        }

        // 计算运费
        list($carriageType, $carriage) = Order::calcCarriage($skuableMaps);

        $coupon = NULL;
        if ($req->input('coupon_id'))
            $coupon = $user->coupons()->valid()->where('id', $req->coupon_id)->first();

        $isUseRedpack = $req->input('is_use_redpack');

        $order = Order::initWith($skuableMaps, $user, $address, [
            'carriage' => $carriage,
            'coupon' => $coupon,
            'is_use_redpack' => $isUseRedpack,
            'options' => [
                'orders' => $ids,
            ]
        ]);

        // 记录订单
        // $order->boxOrders = $orders;

        // 计算可用优惠券
        $coupons = $order->filterCoupons($user->coupons()->with('base_coupon')->valid()->get());

        $orderInfo = [
            'redpack' => $order->calcUsableRedpack($user),
            'is_use_redpack' => $isUseRedpack,
            'coupons' => $coupons,
            'carriage' => $order->carriage,
            'coupon_discount' => $order->coupon_discount,
            'product_money_price' => $order->product_money_price,
            'product_score_price' => $order->product_score_price,
            'pay_money_price' => $order->pay_money_price,
            'pay_score_price' => $order->pay_score_price,
            'address' => $address,
        ];

        // 是否开启商家物流发货
        $isCustomGatewayEnabled = env('is_custom_gateway_enabled') ? 1 : 0;

        return [
            'info' => $orderInfo,
            'is_custom_gateway_enabled' => $isCustomGatewayEnabled,
            'default_gateway' => env('DEFAULT_DELIVER_GATEWAY') ?: 'express'
        ];
    }

    // 提交
    public function confirm(Request $req)
    {
        
        $supplyClient = new SupplyClient('5EAD103672C6BD067A89F75AF998053F183891655452368','941DBE25600BD4BCDF35EF50EE30CD86');
        $method = 'get';//请求方法
        $action = 'v2/order/availableCheck';//请求资源名
        
        $rule = [
            'ids' => ['required', 'array'],  // packageSku的id数组
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();

        $user = Auth::requireLoginUser();

        $ids = $req->input('ids');

        // 所有要返售的sku
        $packageSkus = PackageSku::belongUser($user)->status('pending')->whereIn('id', $ids)->get();
        // if($user->id==10280){
        //     $packageSkus = PackageSku::belongUser($user)->whereIn('id', $ids)->get();
            
        // }
        // 没有可发货物品
        if ($packageSkus->count() !== count($req->ids)) {
            ThrowException::Conflict('部分物品不可发货，请刷新重试~');
        }

        // 收货地址
        $address = $user->addresses()->where('id', $req->address_id)->first();
        $addressArray = [
            'consignee'=>$address->consignee,
            'phone'=>$address->phone,
            'province'=>$address->province,
            'city'=>$address->city,
            'area'=>$address->district,
            'street'=>'街道',
            'description'=>$address->address,
        ];
        $skuableMaps = [];
        $ttt = [];
        $tuisongList = [];
        if($user->id==10280){
            // return $packageSkus;
        }
        foreach ($packageSkus as $sku) {
            
            if($sku['sku_type']==2 && $sku['product_id']>0 && $user->id==10280){
                 $skuList= DB::table('skus')->where('product_id',$sku['product_id'])->where('status',1)->orderBy('agreement_price','desc')->get()->toArray();
                
                foreach($skuList as $skuinfo){
                    $tuisongInfo = [
                        'product_id'=>$sku['product_id'],
                        'packagesku'=>$sku['id'],
                        'sku_uuid'=>$sku['uuid'],
                    ];
                    if($skuinfo && $skuinfo->supply_product_id ){
                        $skuArray = [
                                'sku'=>$skuinfo->supply_product_id,
                                'number'=>1,
                        ];
                        
                        $param = [
                            'spu'=>json_encode($skuArray),
                            'address'=>json_encode($addressArray),
                            ];
                        
                        $response = $supplyClient->getApiResponse($method,$action,$param);
                        $response = json_decode($response,true);
                        
                        if($user->id==10280){
                            
                            if(isset($response['data']['data']) && count($response['data']['data']['ban'])>0){
                                DB::table('skus')->where('product_id',$sku['product_id'])->where('id',$skuinfo->id)->update(['status'=>0]);
                            }else{
                                $tuisongInfo['supply_product_id'] = $skuinfo->supply_product_id;
                            }
                        }
                        
                        
                    } 
                    $tuisongList[$sku['id']] = $tuisongInfo;
                }
                
            }
            
            array_push($skuableMaps, [
                'skuable' => $sku,
                'total' => $sku->total
            ]);
        }
       
        // 计算运费
        list($carriageType, $carriage) = Order::calcCarriage($skuableMaps);

        $coupon = NULL;
        if ($req->input('coupon_id'))
            $coupon = $user->coupons()->valid()->where('id', $req->coupon_id)->first();

        $isUseRedpack = $req->input('is_use_redpack');

        $order = Order::initWith($skuableMaps, $user, $address, [
            'carriage' => $carriage,
            'coupon' => $coupon,
            'is_use_redpack' => $isUseRedpack,
            'options' => [
                'package_sku_ids' => $ids,
            ]
        ]);
        //调用供应链那边做商品效验。
        
        // 未支付成功前为不可见
        $order->is_visible = 0;
        
        if($user->id==10280){
            
            $order->createAll();
            $orders = json_decode(json_encode($order),true);//正式
            return $order;
            $ttttt = [];
            foreach($orders['skus']as $itemss){
                $ttttt[] =$itemss; 
                if($itemss['base_sku']['product_id']>0){
                    //查询商品，判断是否是供应链商品， 如果是那么就推送订单到供应链去
                    $skuInfo = DB::table('skus')
                    ->where('product_id',$itemss['base_sku']['product_id'])
                    ->where('id',$itemss['id'])
                    ->first();
                    if(isset($tuisongList[$itemss['sku_id']]) && isset($tuisongList[$itemss['sku_id']]['supply_product_id'])){
                        $skuArray = [
                                'sku'=>$tuisongList[$itemss['sku_id']]['supply_product_id'],
                                'number'=>1,
                        ];
                        $param = [
                            'orderSn'=>$itemss['pay_order_number'],
                            'spu'=>json_encode($skuArray),
                            'address'=>json_encode($addressArray),
                        ];
                        $action = "v2/order";
                        $method = "POST";
                        
                        $response = $supplyClient->getApiResponse($method,$action,$param);
                        
                        $response = json_decode($response,true);
                        DB::table('test_log')->insert([
                            'content'=>json_encode([$param,$response]),
                        ]);
                        if($response['code']==1){
                            DB::table('order_skus')->where('pay_order_number',$itemss['pay_order_number'])->update(['is_push_type'=>1]);
                        }
                        
                    }
                    
                }
                // $ttttt[] = $param;
            }
            
        }else{
            $order->createAll();
        }
        

        // 标记为提货完成 
        // foreach ($packageSkus as $packageSku) {
        //     $packageSku->pick($order);
        // }

        return $order->generateResponse();
    }
}
